<script lang="ts">
//使用<keep-alive></keep-alive>缓存路由必须显式的声明name
export default {
	name: 'user',
};
</script>

<script setup lang="ts">
import { Search, Plus, Refresh, Setting, EditPen, Delete, Finished, CopyDocument } from '@element-plus/icons-vue';
import { reactive, ref, onMounted, nextTick } from 'vue';
import { get_userinfo, inter_userinfo, update_userinfo, delete_userInfo } from '../../request/api';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';

//搜索表单
const userseachform = reactive({
	name: '',
});

//加载开关
const loading = ref(false);
//用户的表格数据
const usertable = ref([]);
//当前页
const currentPage = ref(1);
//总页数
const total = ref(0);
//每页显示条目个数
const pageSize = ref(10);
//弹出框类型添加还是修改
const dialogtype = ref(0);
//模态框开关
const dialoguser = ref(false);
//用户新增的绑定表单
const userform = reactive({
	user_username: '', //用户名,
	user_password: '', //密码
	user_phone: '', //电话
	user_name: '', //真实姓名
	user_sex: '1', //性别
	user_role: [], //用户选择的角色
	user_branch: [], //用户选择的分店
});
const userid = ref(0); //用户的id
//所有角色
const allrole = ref([]);
//所有分店
const allbranch = ref([]);
//表单规则
const userformrule = reactive({
	user_username: [
		{
			required: true,
			message: '用户名不能为空',
			trigger: 'blur',
		},
		{
			min: 5,
			max: 15,
			message: '请输入5到15个字符',
			trigger: 'blur',
		},
	],
	user_password: [
		{
			type: 'string',
			message: '必须包含大小写字母和数字的组合,长度在6-15之间',
			required: true,
			pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/,
		},
	],
	user_password2: [
		{
			type: 'string',
			message: '必须包含大小写字母和数字的组合,长度在6-15之间',
			pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/,
		},
	],
	user_name: [
		{
			required: true,
			message: '姓名不能为空',
			trigger: 'blur',
		},
	],
	user_phone: [
		{
			type: 'string',
			required: false,
			message: '请输入正确的手机号码',
			pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
		},
	],
});
type FormInstance = InstanceType<typeof ElForm>;
const userformref = ref<FormInstance>();

//刷新数据
const refreshtable = async (currentPage, pagsize) => {
	loading.value = true;
	const { data } = await get_userinfo(currentPage, pagsize);
	if (data.code == 200) {
		console.log(data.data);
		total.value = data.data.total;
		usertable.value = data.data.data;
		loading.value = false;
	}
};

//页面进入请求数据
const { data } = await get_userinfo(1, pageSize.value);
if (data.code == 200) {
	console.log(data.data);
	total.value = data.data.total;
	usertable.value = data.data.data;
	allrole.value = data.allrole;
	allbranch.value = data.allbranch;
	console.log(data);
}

//关闭模态框之前要做的
const beforeclosedialog = (done) => {
	//清空表单数据
	userformref.value!.resetFields();
	return done(false);
};
//表单的确认按钮
const dialoguserclick = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async (valid) => {
		if (valid) {
			if (dialogtype.value == 0) {
				console.log(userform);
				//新增
				const { data } = await inter_userinfo(userform);
				if (data.code == 200) {
					ElMessage.success('新增成功');
					userformref.value!.resetFields();
					refreshtable(currentPage.value, pageSize.value);
					dialoguser.value = false;
				} else if (data.code == -2) {
					//表示用户名重复
					ElMessage.error(data.msg);
					userform.user_username = '';
				} else {
					ElMessage.error(data.msg);
				}
			} else {
				//修改呗
				const { data } = await update_userinfo(userform, userid.value);
				console.log(userform);
				if (data.code == 200) {
					ElMessage.success(data.msg);
					userformref.value!.resetFields();
					dialoguser.value = false;
					refreshtable(currentPage.value, pageSize.value);
				} else {
					ElMessage.error(data.msg);
					console.log(data);
				}
			}
		} else {
			console.log('验证失败');
		}
	});
};

//点击修改按钮
const updateclick = (row) => {
	dialogtype.value = 1;
	dialoguser.value = true;
	nextTick(() => {
		userform.user_name = row.user_name;
		userform.user_password = row.user_password;
		userform.user_phone = row.user_phone;
		row.role.forEach((element) => {
			userform.user_role.push(element.role_id);
		});

		row.branch.forEach((element) => {
			userform.user_branch.push(element.branch_id);
		});
		// userform.user_role = row.role;
		userform.user_sex = row.user_sex == '男' ? '1' : '2';
		userform.user_username = row.user_username;
	});
	userid.value = row.user_id;
	console.log(row);
};

//点击删除按钮
const delclick = async (row) => {
	console.log(row.user_id);
	const { data } = await delete_userInfo(row.user_id);
	if (data.code == 200) {
		ElMessage.success(data.msg);
		refreshtable(currentPage.value, pageSize.value);
	} else {
		ElMessage.error(data.msg);
	}
};
//点击状态开关
const switchlick = async (row) => {
	const { data } = await update_userinfo({ user_switch: row.user_switch }, row.user_id);
	if (data.code == 200) {
		ElMessage.success(data.msg);
	} else {
		ElMessage.error(data.msg);
		refreshtable(currentPage.value, pageSize.value);
	}
};

//监听current-page事件
const handleCurrentChange = async (newpage) => {
	refreshtable(newpage, pageSize.value);
};

//监听page-size每页条数
const handleSizeChange = async (pagesize) => {
	refreshtable(currentPage.value, pagesize);
};
</script>

<template>
	<div class="el-card_body">
		<el-form class="roleformclass" :inline="true" :model="userseachform" label-width="80px">
			<el-form-item label="用户名称:">
				<el-input v-model="userseachform.name" placeholder="请输入用户名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search">查询</el-button>
				<el-button>重置</el-button>
			</el-form-item>
		</el-form>

		<el-table v-loading="loading" :data="usertable" height="calc(100vh - 300px)" style="width: 100%">
			<el-table-column label="Address Info">
				<template #header>
					<div class="ele-table-tool ele-table-tool-default">
						<el-button
							type="primary"
							:icon="Plus"
							@click="
								dialoguser = true;
								dialogtype = 0;
							"
							>添加</el-button
						>
						<div class="ele-tool">
							<el-tooltip effect="dark" content="刷新" placement="top">
								<el-button size="small" @click="refreshtable(currentPage, pageSize)" :icon="Refresh"></el-button>
							</el-tooltip>

							<el-tooltip effect="dark" content="列设置" placement="top">
								<el-button size="small" :icon="Setting"></el-button>
							</el-tooltip>
						</div>
					</div>
				</template>
				<el-table-column align="center" type="index" width="50" />
				<el-table-column prop="user_username" label="用户账号" align="center" width="180" />
				<el-table-column prop="user_name" label="姓名" align="center" width="180" />
				<el-table-column prop="user_sex" label="性别" align="center" width="80" />
				<el-table-column prop="user_phone" label="手机号" align="center" width="180" />
				<el-table-column prop="role" label="角色" align="center" width="180">
					<template #default="scope">
						<el-tag style="margin-left: 12px" v-for="(item, index) in scope.row.role">
							{{ item.role_name }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="branch" label="分店" align="center" width="180">
					<template #default="scope">
						<el-tag type="success" style="margin-left: 12px" v-for="(item, index) in scope.row.branch">{{ item.branch_name }}</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="user_creationtime" label="创建时间" />
				<el-table-column prop="user_updatime" label="修改时间" />

				<el-table-column prop="user_switch" label="状态" align="center" width="80">
					<template #default="scope">
						<el-switch v-model="scope.row.user_switch" :active-value="1" :inactive-value="0" @change="switchlick(scope.row)" />
					</template>
				</el-table-column>
				<el-table-column fixed="right" align="center" label="操作" width="150">
					<template #default="scope">
						<el-button type="text" @click="updateclick(scope.row)" :icon="EditPen">修改</el-button>

						<el-popconfirm @confirm="delclick(scope.row)" title="是否确认删除?">
							<template #reference>
								<el-button class="operate" type="text" :icon="Delete">删除</el-button>
							</template>
						</el-popconfirm>
						<!-- <el-button type="text" class="reset" :icon="CopyDocument">重置密码</el-button> -->
					</template>
				</el-table-column>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<div class="ele-pagination">
			<el-pagination v-model:currentPage="currentPage" :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper" :total="total" @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange" />
		</div>
	</div>
	<!-- 用户新增和修改的弹出框-->
	<el-dialog :before-close="beforeclosedialog" :title="dialogtype == 0 ? '新增' : '修改'" v-model="dialoguser" width="25%">
		<el-form ref="userformref" :model="userform" :rules="userformrule" label-width="85px">
			<el-form-item label="用户名:" prop="user_username">
				<el-input :disabled="dialogtype == 1 ? true : false" placeholder="请输入用户名" v-model="userform.user_username"></el-input>
			</el-form-item>
			<el-form-item label="密码:" :prop="dialogtype == 0 ? 'user_password' : 'user_password2'">
				<el-input placeholder="必须包含大小写字母和数字的组合,长度在6-15之间" type="password" show-password v-model="userform.user_password"></el-input>
			</el-form-item>
			<el-form-item label="姓名:" prop="user_name">
				<el-input placeholder="请输入姓名" v-model="userform.user_name"></el-input>
			</el-form-item>
			<el-form-item label="性别:" prop="user_sex">
				<el-select v-model="userform.user_sex" placeholder="请选择性别">
					<el-option label="男" value="1" />
					<el-option label="女" value="2" />
				</el-select>
			</el-form-item>
			<el-form-item label="手机号:" prop="user_phone">
				<el-input placeholder="请输入手机号" v-model="userform.user_phone"></el-input>
			</el-form-item>
			<el-form-item label="角色:" prop="user_role">
				<el-select multiple v-model="userform.user_role" placeholder="请选择角色">
					<el-option v-for="item in allrole" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
				</el-select>
			</el-form-item>

			<el-form-item label="分店:" prop="user_branch">
				<el-select multiple v-model="userform.user_branch" placeholder="请选择分店">
					<el-option v-for="item in allbranch" :key="item.branch_id" :label="item.branch_name" :value="item.branch_id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="(dialoguser = false), userformref!.resetFields()">取消</el-button>
				<el-button type="primary" @click="dialoguserclick(userformref)">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<style lang="less" scoped>
.el-card_body {
	background-color: white;
	padding: 15px;
}
.roleformclass {
	margin-bottom: 15px;
}
/deep/.roleformclass.el-form--inline .el-form-item {
	margin-right: 15px;
}
.ele-table-tool {
	display: inline-flex;
	flex-wrap: wrap;
	width: 100%;
}
.ele-tool {
	margin: 5px 0 5px auto;
}

.ele-pagination {
	margin-top: 15px;
	display: flex;
	justify-content: center;
}
/deep/ .operate {
	color: red;
}
/deep/.reset {
	color: #52c41a;
}
</style>
